package com.pyb.common.exception;

import com.pyb.common.upload.controller.model.GeneralJsonResult;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * HandlerExceptionWrapperResolver
 *
 * @author chuchen.zhang
 * @date 17-2-25 下午11:40
 */
public class HandlerExceptionWrapperResolver implements HandlerExceptionResolver {

	private static final Logger logger = LoggerFactory.getLogger(HandlerExceptionWrapperResolver.class);

	private HttpMessageConverter jsonMessageConverter;

	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		GeneralJsonResult result = resolveException(ex);
		HttpOutputMessage outputMessage = new ServletServerHttpResponse(response);
		try {
			//将exceptionResultInfo对象转成json输出
			jsonMessageConverter.write(result, MediaType.APPLICATION_JSON, outputMessage);
		} catch (Exception e) {
			logger.error("resolve exception error", e);
		}
		return new ModelAndView();
	}

	// 异常信息解析方法
	private GeneralJsonResult resolveException(Exception exception) {
		GeneralJsonResult result = new GeneralJsonResult();
		result.setRet(false);
		result.setErrorCode("500");

		if (exception instanceof BizException) {
			// 抛出的是系统自定义异常
			String errorMsg = ((BizException) exception).getErrorMsg();
			result.setErrorMsg(errorMsg);
			logger.error(errorMsg, exception);
		} else {
			result.setErrorMsg("未知错误！");
			logger.error("uncatched exception!", exception);
		}
		return result;
	}

	public HttpMessageConverter getJsonMessageConverter() {
		return jsonMessageConverter;
	}

	public void setJsonMessageConverter(HttpMessageConverter jsonMessageConverter) {
		this.jsonMessageConverter = jsonMessageConverter;
	}
}
